<!--
 * @Descripttion: 下拉菜单
 * @Author: armin
 * @Date: 2021-07-16 14:23:19
 * @LastEditors: armin
 * @LastEditTime: 2021-09-09 11:42:55
-->
<template>
  <div class="dropdown" ref="dropdownRef">
    <a
      href="#"
      class="btn btn-outline-light my-2 dropdown-toggle"
      @click.prevent="toggleOpen"
    >
      {{ title }}
    </a>
    <ul class="dropdown-menu" :style="{ display: 'block' }" v-if="isOpen">
      <slot></slot>
    </ul>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, watch } from 'vue'
import useClickOutside from '@/hooks/useClickOutside'
export default defineComponent({
  name: 'DropdownMenu',
  props: {
    title: {
      type: String,
      required: true
    }
  },
  setup () {
    const isOpen = ref(false) // 下拉列表是否展示，默认关闭
    const dropdownRef = ref<null | HTMLElement>(null) // 获取上面ref="dropdownRef"DOM节点
    const toggleOpen = () => { // 下拉列表的展示与隐藏
      isOpen.value = !isOpen.value
    }
    const isClickOutside = useClickOutside(dropdownRef)
    watch(isClickOutside, () => {
      if (isOpen.value && isClickOutside.value) {
        // 如果下拉菜单显示并且鼠标点击到了外面，就关闭下拉菜单
        isOpen.value = false
      }
    })
    return {
      isOpen,
      dropdownRef, // 这里的名字必须和上面ref=的名字相同
      toggleOpen
    }
  }
})
</script>
